<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<!--<el-form-item>
					<el-date-picker type="datetime" placeholder="开始时间" v-model="filters.startTime" :picker-options="pickerBeginDateBefore"></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-date-picker type="datetime" placeholder="结束时间" v-model="filters.endTime" :picker-options="pickerBeginDateAfter" ></el-date-picker>
				</el-form-item>-->
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="输入品牌名称查找"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getUsers">查找</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" >新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table :data="users" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="index" label="序号" width="75" align="center">
			</el-table-column>
			<el-table-column prop="logo" label="品牌LOGO" align="center">
				<template slot-scope="scope">
					<img :src="scope.row.logo" width="40" height="40" align="center" />
				</template>
			</el-table-column>
			<el-table-column prop="name" label="名称" align="center">
			</el-table-column>
			<el-table-column prop="introduce" label="品牌介绍" align="center">
			</el-table-column>
			<el-table-column prop="creatTime" label="创建时间" align="center" :formatter="formatDateTime">
			</el-table-column>
			<el-table-column label="操作" align="center">
				<template slot-scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<div class="toolbar" style="display: flex;justify-content: flex-end;">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="currentPage"
				:page-sizes="[10, 20, 30, 40]"
				:page-size="size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total">
			</el-pagination>
		</div>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="品牌名称" prop="name">
					<el-input v-model="editForm.name" placeholder="输入品牌名称，不超过20字" :maxlength="20" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="品牌介绍" prop="introduce">
					<el-input type="textarea" placeholder="输入品牌介绍" v-model="editForm.introduce" :maxlength="100"></el-input>
				</el-form-item>
				<el-form-item label="品牌LOGO">
					<el-upload class="upload-demo" action="/file/upload"
					           name="file"
					           :data="fileType"
					           :on-success="onSuccess1"
					           :on-error="onError1"
					           :on-remove="handleRemove1"
					           list-type="picture-card"
					           :file-list="fileList"
					>
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增品牌" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="品牌名称" prop="name">
					<el-input v-model="addForm.name" placeholder="输入品牌名称，不超过20字" :maxlength="20" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="品牌介绍" prop="introduce">
					<el-input type="textarea" placeholder="输入品牌介绍" v-model="addForm.introduce" :maxlength="100"></el-input>
				</el-form-item>
				<el-form-item label="品牌LOGO">
					<el-upload class="avatar-uploader" action="/file/upload"
							   name="file"
							   :data="fileType"
							   :on-success="onSuccess2"
							   :on-error="onError2"
							   :show-file-list="false"
							   :on-remove="handleRemove2"
					>
						<img v-if="addForm.logo" :src="addForm.logo" class="avatar">
  						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import { brandList, addGoodsBrand, editGoodsBrand, deleteGoodsBrand } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					keyword: '',
					startTime:null,
					endTime:null
				},
				pickerBeginDateBefore:{
		            disabledDate: (time) => {
		                let beginDateVal = this.filters.endTime;
		                if (beginDateVal) {
		                    return time.getTime() > beginDateVal;
		                }
		            }
		        },
		        pickerBeginDateAfter:{
		            disabledDate: (time) => {
		                let beginDateVal = this.filters.startTime;
		                if (beginDateVal) {
		                    return time.getTime() < beginDateVal;
		                }
		            }
		        },
				users: [
				// {
				// 	id:"1",
				// 	name:"上好佳",
				// 	logo:"",
				// 	introduce:"上好佳是最好吃的！",
				// 	creatTime:''
				// }
				],
				total: 0,
				currentPage: 1,
				size:10,
				tempLogo:'',
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '输入品牌名称，不超过20字', trigger: 'blur' }
					],
					introduce:[
						{ required: true, message: '输入品牌介绍', trigger: 'blur' }
					],
				},
				//编辑界面数据
				editForm: {
					id:"",
					name:"",
					logo:"",
					introduce:""
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '输入品牌名称，不超过20字', trigger: 'blur' }
					],
					introduce:[
						{ required: true, message: '输入品牌介绍', trigger: 'blur' }
					],
				},
				//新增界面数据
				addForm: {
					name:"",
					logo:"",
					introduce:""
				},
				fileType:{
		          "fileType" : "SUMMARY_EVENT"
		        },
		        fileList: [],
		        fileType2:{
		          "fileType" : "SUMMARY_EVENT"
		        },
		        fileList2: [],

			}
		},
		methods: {
			formatDateTime: function (row, column){
				var date = row[column.property];
				if (date == undefined) {
		            return "";
		        }
				return this.moment(date).format("YYYY-MM-DD HH:mm:ss");
			},
			changeToDateStr:function(date){
				return this.moment(date).format("YYYY-MM-DD HH:mm:ss");
			},
			//获取用户列表
			getUsers() {
				let para = {
					pageIndex: this.currentPage,
					pageSize:this.size,
					startTime:this.filters.startTime,
					endTime:this.filters.endTime,
					keyword: this.filters.keyword
				};
				if (!para.startTime || para.startTime=='') {
					para.startTime = null;
				}else{
					para.startTime = this.changeToDateStr(para.startTime);
				}
				if (!para.endTime || para.endTime=='') {
					para.endTime = null;
				}else{
					para.endTime = this.changeToDateStr(para.endTime);
				}
				this.listLoading = true;
				//NProgress.start();
				console.log(para);
				brandList(para).then((res) => {
					console.log(res);
					this.listLoading = false;
					if (res.code == 0){
						this.users = res.data.data;
						this.total = res.data.totalCount
					}else{
						this.$message({
							message: res.message,
							type: 'error'
						});
					}
					//NProgress.done();
				});
			},
			// 分页详情
			handleSizeChange(val) {
				this.size = val;
				this.getUsers();
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getUsers();
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					console.log(para);
					deleteGoodsBrand(para).then((res) => {
						console.log(res);
						this.listLoading = false;
						//NProgress.done();
						if (res.code == 0) {
							this.$message({
								message: '删除成功',
								type: 'success'
							});
							this.getUsers();
						}else{
							this.$message({
								message: res.message,
								type: 'error'
							});
						}
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editFormVisible = true;
				var tempObj = Object.assign({}, row);
				this.editForm = {
					id:tempObj.id,
					name:tempObj.name,
					logo:tempObj.logo,
					introduce:tempObj.introduce
				};
				this.tempLogo = this.editForm.logo;
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
							console.log(para);
							editGoodsBrand(para).then((res) => {
								console.log(para);
								this.editLoading = false;
								if (res.code == 0) {
									this.$message({
										message: '提交成功',
										type: 'success'
									});
									this.$refs['editForm'].resetFields();
									this.editFormVisible = false;
									this.getUsers();
								}else{
									this.$message({
										message: res.message,
										type: 'error'
									});
								}
								//NProgress.done();

							});
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
							console.log(para);
							addGoodsBrand(para).then((res) => {
								console.log(res);
								this.addLoading = false;
								//NProgress.done();
								if (res.code == 0) {
									this.$message({
										message: '提交成功',
										type: 'success'
									});
									this.$refs['addForm'].resetFields();
									this.addFormVisible = false;
									this.getUsers();
								}else{
									this.$message({
										message: res.message,
										type: 'error'
									});
								}
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					deleteGoodsBrand(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			},
			onSuccess1(response, file, fileList1) {
				console.log(file.response.body)
		       this.editForm.logo = file.response.body;
		       //console.log("图片上传成功："+URL.createObjectURL(file.raw));
		    },

			onError1(response, file, fileList1) {
		        this.$message({
		          showClose: true,
		          message: '图片上传失败！',
		          type: 'error'
		        });
		      },
		    handleRemove1(file,fileList){
		    	console.log("选择图片："+file.response.body);
		    	this.editForm.logo = null;
		    },
		    handleExceed1(files, fileList1) {
		        this.$message.warning(`当前超出限制！本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList1.length} 个文件`);
		    },
		    delPics:function(value){
		    	console.log("删除图片:"+value);
		    	this.editForm.logo = null;
		    },
			onSuccess2(response, file, fileList1) {
		       this.addForm.logo=URL.createObjectURL(file.raw);
		       console.log("图片上传成功："+URL.createObjectURL(file.raw));
		       // this.editForm.imgName = file.name;
		    },

			onError2(response, file, fileList1) {
		        this.$message({
		          showClose: true,
		          message: '图片上传失败！',
		          type: 'error'
		        });
		      },
		    handleRemove2(file,fileList){
		    	console.log("选择图片："+URL.createObjectURL(file.raw));
		    	this.addForm.logo = null;
		    },
		    handleExceed2(files, fileList) {
		        this.$message.warning(`当前超出限制！本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList2.length} 个文件`);
		    },

		    onSuccessUpdate(response, file, fileList1) {
		        this.editForm.logo = URL.createObjectURL(file.raw);;
		    },
		    onErrorUpdate(response, file, fileList1){
		        this.$message({
		          showClose: true,
		          message: '图片上传失败！',
		          type: 'error'
		        });
		    }
		},
		mounted() {
			this.getUsers();
		}
	}

</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
  	border: solid 1px #ccc;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
